package com.striver.registry.config.nacos;

import com.alibaba.cloud.nacos.ConditionalOnNacosDiscoveryEnabled;
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.NacosServiceManager;
import com.alibaba.cloud.nacos.discovery.NacosDiscoveryAutoConfiguration;
import com.alibaba.cloud.nacos.registry.NacosServiceRegistry;
import com.alibaba.nacos.api.naming.NamingService;
import com.striver.registry.properties.StriverRegistyProperties;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

@Configuration
@ConditionalOnNacosDiscoveryEnabled
@EnableConfigurationProperties(StriverRegistyProperties.class)
@AutoConfigureBefore(NacosDiscoveryAutoConfiguration.class)
public class NacosRegistryConfig {

    private static final String SERVER_ADDR = "%s:%s";
    @Resource
    private NacosServiceManager nacosServiceManager;
    @Resource
    private StriverRegistyProperties striverRegistyProperties;
    @Bean
    public NacosServiceRegistry nacosServiceRegistry(NacosDiscoveryProperties nacosDiscoveryProperties) {
        initNacosDiscoveryProperties(nacosDiscoveryProperties);
        return new NacosServiceRegistry(nacosDiscoveryProperties);
    }

    @Bean
    public NamingService initNamingService(NacosDiscoveryProperties nacosDiscoveryProperties) {
        initNacosDiscoveryProperties(nacosDiscoveryProperties);
        return nacosServiceManager.getNamingService(nacosDiscoveryProperties.getNacosProperties());
    }

    private void initNacosDiscoveryProperties(NacosDiscoveryProperties nacosDiscoveryProperties) {
        nacosDiscoveryProperties.setServerAddr(String.format(SERVER_ADDR, striverRegistyProperties.getHost(), striverRegistyProperties.getPort()));
        nacosDiscoveryProperties.setRegisterEnabled(StriverRegistyProperties.Type.nacos.equals(striverRegistyProperties.getType()));
    }
}
